package com.surverycomp.models;

import java.util.ArrayList;
import java.util.List;

import javax.jdo.annotations.IdGeneratorStrategy;
import javax.jdo.annotations.PersistenceCapable;
import javax.jdo.annotations.Persistent;
import javax.jdo.annotations.PrimaryKey;

import org.json.JSONException;
import org.json.JSONObject;

import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;

@PersistenceCapable
public class User {

	@PrimaryKey
	@Persistent(valueStrategy = IdGeneratorStrategy.IDENTITY)
	Key key;
	@Persistent
	String phoneNumber;
	@Persistent
	String name;
	@Persistent
	Key event;
	@Persistent
	private int score;
	@Persistent
	List<Key> facedChallenges = new ArrayList<Key>();

	public User(String phoneNumber, Key eventkey) {
		this.phoneNumber = phoneNumber;
		this.name = "noname";
		this.event = eventkey;
	}

	public User(JSONObject object) throws JSONException {
		this.name = object.getString("name");
		this.phoneNumber = object.getString("phoneNumber");
		this.key = KeyFactory.createKey(User.class.getSimpleName(),
				object.getLong("key"));
	}

	public User(String phoneNumber, String name, Key eventkey) {
		this.phoneNumber = phoneNumber;
		this.name = name;
		this.event = eventkey;
	}

	public void addChallengeFaced(Challenge c) {
		this.facedChallenges.add(c.getKey());
	}

	public String getPhoneNumber() {
		return phoneNumber;
	}

	public void setPhoneNumber(String phoneNumber) {
		this.phoneNumber = phoneNumber;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public Key getEvent() {
		return event;
	}

	public void setEvent(Key event) {
		this.event = event;
	}

	public List<Key> getFacedChallenges() {
		return facedChallenges;
	}

	public void setChallenges(List<Key> challenges) {
		this.facedChallenges = challenges;
	}

	public Key getKey() {
		return key;
	}

	public void setKey(Key key) {
		this.key = key;
	}

	public JSONObject getJSON() throws JSONException {
		JSONObject object = new JSONObject();
		object.put("key", key.getId());
		object.put("name", name);
		object.put("phoneNumber", phoneNumber);
		return object;
	}

	@Override
	public String toString() {
		return "[name: " + name + ", " + ", key: " + key.getId()
				+ " phoneNumber: " + phoneNumber + "]";
	}

	@Override
	public boolean equals(Object other) {
		if (other == null)
			return false;
		if (other instanceof User) {
			User user = (User) other;
			boolean equals = true;
			if (name != null)
				equals &= name.equals(user.name);
			if (phoneNumber != null)
				equals &= phoneNumber.equals(user.phoneNumber);
			if (key != null)
				equals &= key.equals(user.key);
			return equals;
		}
		return false;
	}

	public int getScore() {
		return score;
	}

	public void setScore(int score) {
		this.score = score;
	}
}
